package ca.intelliware.commons.virtualization.vmware;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import ca.intelliware.commons.virtualization.Host;
import ca.intelliware.commons.virtualization.VMachine;

import com.vmware.vim25.mo.HostSystem;
import com.vmware.vim25.mo.VirtualMachine;

public class VmHost implements Host {
	private HostSystem host;
	private String hostName;
	
	public String getId() {
		if (hostName == null) {
			hostName = host.getName();
		} 
		return hostName;
	}

	VmHost(HostSystem host) {
		this.host = host;
	}

	public VMachine virtualMachine(
			String id) throws IOException {
		VMachine foundVm = null;
		for (VMachine vm : virtualMachines()) {
			if (vm.getId().equalsIgnoreCase(id)) {
				foundVm = vm;
				break;
			}
		}
		return foundVm;
	}

	public Collection<VMachine> virtualMachines() throws IOException {
		
		VirtualMachine[] vim25VirtualMachines = this.host
				.getVms();
		List<VMachine> vms = new ArrayList<VMachine>(
				vim25VirtualMachines.length);
		for (VirtualMachine vim25VirtualMachine : vim25VirtualMachines) {
			vms.add(new Vm(vim25VirtualMachine));
		}
		return vms;
	}

	public String inventoryReport() throws Exception {
		StringBuilder strBuilder = new StringBuilder();
		strBuilder.append("      ").append(this.getId()).append("\n");
		strBuilder.append("         ");
		for (VMachine vmMachine : virtualMachines()) {
			strBuilder.append(vmMachine.getId()).append(",");
		}
		strBuilder.append("\n");
		return strBuilder.toString();
	}

	public void revertAllVirtualMachinesToLastSnapshot() throws Exception {
		for (VMachine vm : virtualMachines()) {
			vm.revertToLastSnapshot();
		}

	}

}
